<?php

namespace App\Http\Controllers\Admin;

use App\Exports\CashOutExport;
use App\Http\Controllers\Controller;
use App\Models\CashOuts;
use App\Models\BalanceLogs;
use App\Models\Mails;
use App\Models\Users;
use App\Models\MailTemplates;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class CashOutController extends Controller {

    /**
     * 页面
     * @return view
     */
    public function index(){
        return view('admin.user.cash_out');
    }

    /**
     * 列表数据
     * @param Request $request
     * @return bool
     */
    public function list(Request $request){
        try{
            $params = [
                'kwd' => (string)$request->get('kwd',''),
                'status' => (int)$request->get('status',0),
                'start' => (string)$request->get('start',''),
                'end' => (string)$request->get('end',''),
                'sort' => (string)$request->get('sort',''),
            ];
            $lists = CashOuts::getList($params);
            return $this->writeJson(0,$lists);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 查看
     * @param Request $request
     * @return bool|view
     */
    public function edit(Request $request){
        try{
            $id = (int)$request->get('id',0);
            $info = [];
            if($id){
                $info = CashOuts::findOrFail($id);
                if($info['pay_type'] == 1){
                	$info['pay_type_text'] = "银行卡";
                }elseif ($info['pay_type'] == 2){
                	$info['pay_type_text'] = "支付宝";
                }else{
                	$info['pay_type_text'] = "微信";
                }
            }
            $info = json_encode($info);

            return view('admin.user.cash_detail',compact('info','id'));
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 激活
     * @param Request $request
     * @return bool
     */
    public function active(Request $request){
        try{
            $id = (int)$request->get('id',0);
            if(empty($id)){
                return $this->writeJson(1,null,'参数错误');
            }
            $info = CashOuts::findOrFail($id);
			$user_info = Users::findOrFail($info['user_id']);
			if($user_info['status'] == -1 || $user_info['status'] == 4){
				return $this->writeJson(1,null,'该用户处于黑名单中，不能执行该操作');
			}                      
            if($info['pay_type'] == 1){
            	$msg = $info['user_name']."悬赏达人，您的提现金额：".$info['amount']."，已发，支付银行卡".$info['bank_no']."，请注意查收。祝您任务愉快";
            }elseif ($info['pay_type'] == 2){
            	$msg = $info['user_name']."悬赏达人，您的提现金额：".$info['amount']."，已发支付支付宝账号：".$info['paycount']."，请注意查收。祝您任务愉快";
            	//xx悬赏猎人，您的提现金额xx，已发支付微信号xx，请注意查收。祝您任务愉快
            }else{
            	$msg = $info['user_name']."悬赏达人，您的提现金额：".$info['amount']."，已发支付微信号：".$info['paycount']."，请注意查收。祝您任务愉快";
            }
            $template = array();
            $template['user_id'] = $info['user_id'];
            $template['title'] = "提现申请通过";
            $template['content'] = $msg;
            $template['status'] = 1;
            $template['type'] = 1;
            Mails::create($template);
			//增加用户已提现金额
            Users::where('id',$info['user_id'])->increment('amount',$info['amount']);
			//修改提现状态
            $info->update(['status' => CashOuts::STATUS_2 , 'payment_admin' => auth()->guard('admin')->user()->username , 'payment_time' => date('Y-m-d H:i:s')]);
            
            //生成财务记录
            $balance = [
            		'user_id' =>  $info['user_id'],
            		'user_name' => $user_info['true_name']?$user_info['true_name']:$user_info['nickname'],
            		'money' => $info['amount'],
            		'balance' => '-'.$info['amount'],           		 
            		'desc' => '余额提现',
            		'type' => 2,
            ];
            $balance_info = BalanceLogs::create($balance);
            
            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 激活
     * @param Request $request
     * @return bool
     */
    public function update(Request $request){
    	try{
    		$data = $request->all();
    		
    		if(!$data['id']){
    			return $this->writeJson(0, null, '数据异常');
    			
    		}
    		$id = $data['id'];
    		$info = CashOuts::findOrFail($id);
    		$user_info = Users::findOrFail($info['user_id']);
    		
    		if($data['status'] == 2){
    			if($info['pay_type'] == 1){
    				$msg = $info['user_name']."悬赏达人，您的提现金额：".$info['amount']."，已发，支付银行卡".$info['bank_no']."，请注意查收。祝您任务愉快";
    			}elseif ($info['pay_type'] == 2){
    				$msg = $info['user_name']."悬赏达人，您的提现金额：".$info['amount']."，已发支付支付宝账号：".$info['paycount']."，请注意查收。祝您任务愉快";
    				//xx悬赏猎人，您的提现金额xx，已发支付微信号xx，请注意查收。祝您任务愉快
    			}else{
    				$msg = $info['user_name']."悬赏达人，您的提现金额：".$info['amount']."，已发支付微信号：".$info['paycount']."，请注意查收。祝您任务愉快";
    			}
    			$template = array();
    			$template['user_id'] = $info['user_id'];
    			$template['title'] = "提现申请通过";
    			$template['content'] = $msg;
    			$template['status'] = 1;
    			$template['type'] = 1;
    			Mails::create($template);
    			//增加用户已提现金额
    			Users::where('id',$info['user_id'])->increment('amount',$info['amount']);
    			//修改提现状态
    			$info->update(['status' => CashOuts::STATUS_2 , 'payment_admin' => auth()->guard('admin')->user()->username , 'payment_time' => date('Y-m-d H:i:s')]);
    			
    			//生成财务记录
    			$balance = [
    					'user_id' =>  $info['user_id'],
    					'user_name' => $user_info['true_name']?$user_info['true_name']:$user_info['nickname'],
    					'money' => $info['amount'],
    					'balance' => '-'.$info['amount'],
    					'desc' => '余额提现',
    					'type' => 2,
    			];
    			$balance_info = BalanceLogs::create($balance);
    			
    			return $this->writeJson(0);
    		}else{
    			$msg = "您的提现申请被驳回，理由是：".$data['remark'];
    			
    			$template = array();
    			$template['user_id'] = $info['user_id'];
    			$template['title'] = "提现被拒";
    			$template['content'] = $msg;
    			$template['status'] = 1;
    			$template['type'] = 1;
    			Mails::create($template);
    			//还回用户余额
    			Users::where('id',$info['user_id'])->increment('balance',$info['useramount']);
    			//修改提现状态
    			$info->update(['status' => $data['status'] ,'remark'=>$data['remark'], 'payment_admin' => auth()->guard('admin')->user()->username , 'payment_time' => date('Y-m-d H:i:s')]);
    			return $this->writeJson(0, null, '操作成功');
    		}
     	}catch (\Exception $e){
    		return $this->writeJson(1,null,$e->getMessage());
    	}
    }
    
    /**
     * 单个/多个删除
     * @param Request $request
     * @return bool
     */
    public function destroy(Request $request){
        try{
            $id = $request->get('id');
            if(empty($id)){
                return $this->writeJson(1,null,'参数错误');
            }
            if(is_array($id)){
                $where['id'] = ['in',$id];
            }else{
                $where['id'] = $id;
            }
            //修改软删除 19-7-31
            $data['status'] = -1;
            CashOuts::where($where)->update($data);
            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     *  Excel导出
     * @param Request $request
     * @return bool
     */
    public function exports(Request $request)
    {
        $ids = $request->get('ids');
        $export = new CashOutExport($ids);
        //这里可以传参到服务层
        return Excel::download($export, '提现表.xlsx');
    }

    /**
     * 通知消息 内容转换函数
     *
     * @param string $message 内容模板
     * @param array $param 内容参数数组
     * @return string 通知内容
     */
    function ds_replace_text($message, $param)
    {
        if (!is_array($param))
            return false;
        foreach ($param as $k => $v) {
            $message = str_replace('{$' . $k . '}', $v, $message);
        }
        return $message;
    }
}
